package com.zhzhinn.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.BannerComponent;
import com.edgclub.edg.adapter.adapteruitls.MyItemClickListener;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.fragment.GzBaseFragment;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.AaskBeanData;
import com.edgclub.edg.model.Banner;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.Topic;
import com.edgclub.edg.model.TopicChannel;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.BannerListData;
import com.edgclub.edg.model.result.TopicBBData;
import com.edgclub.edg.model.result.TopicListData;
import com.edgclub.edg.uc.autoscrollviewpager.AutoScrollViewPager;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.TopicPrefUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;
import com.zhzhinn.adapter.InnAdapter;
import com.zhzhinn.adapter.RoomAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class InnFragment extends GzBaseFragment implements View.OnClickListener {

    private static final String TOPIC_TYPE = "topic_type";
    private static final String ARG_CHANNEL = "channel";
    private Activity mActivity;
    private int topic_type;
    private TopicChannel channel;  //频道

    private int currPage = 1;
    private int pageSize = 20;
    private XRecyclerView recyclerView;
    private InnAdapter bbAdapter;
    private List<Topic> topicList;

    //头部
//    private View headView;
//    private FrameLayout ll_banner;
//    private AutoScrollViewPager banner_viewPager;
//    private LinearLayout viewGroup;
//    private BannerComponent bannerCommon;

    private UserPrefUtils userPrefUtils;
    private TopicPrefUtils topicPrefUtils;
    private TopicApi topicApi;
    private TextView text_empty;
    private ImageView imageView_empty;
    private LinearLayout layout_empty;
    private boolean isFirstLoad = true;


    public static InnFragment newInstance(int topic_type, TopicChannel channel) {
        InnFragment f = new InnFragment();
        Bundle args = new Bundle();
        args.putInt(TOPIC_TYPE, topic_type);
        args.putSerializable(ARG_CHANNEL, channel);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = this.getActivity();
        return inflater.inflate(R.layout.fragment_bb, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        topic_type = getArguments().getInt(TOPIC_TYPE, 1);
        channel = (TopicChannel) getArguments().getSerializable(ARG_CHANNEL);

        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (recyclerView != null && isFirstLoad) {
                isFirstLoad = false;
                getEdg(currPage);
            }
//            if(bannerCommon!=null){
//                bannerCommon.startAutoScroll();
//            }

        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void initView(View view) {
        initLoadView(view);
        layout_empty= (LinearLayout) view.findViewById(R.id.layout_empty);;
        text_empty= (TextView)  view.findViewById(R.id.text_empty);;
        imageView_empty = (ImageView)  view.findViewById(R.id.imageView_empty);
        imageView_empty.setVisibility(View.VISIBLE);
        imageView_empty.setImageResource(R.drawable.nomess);
        text_empty.setText("你还没有关注任何人哦，快去添加一些感兴趣的人吧");
        recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

//        headView =   LayoutInflater.from(mActivity).inflate(R.layout.head_bb, (ViewGroup)mActivity.findViewById(android.R.id.content),false);
//        initHeadView(headView);
//        recyclerView.addHeaderView(headView);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getEdg(currPage);
            }

            @Override
            public void onLoadMore() {
                getEdg(currPage);
            }
        });


    }

    private void initData() {
        topicApi = new TopicApi(getActivity());
        userPrefUtils = new UserPrefUtils(getActivity());
        topicPrefUtils = new TopicPrefUtils(getActivity());
        topicList = new ArrayList<>();

        bbAdapter = new InnAdapter(getActivity());
        bbAdapter.setDatas(topicList);
        recyclerView.setAdapter(bbAdapter);

        if (channel != null && channel.getChannelId().equals(BBConstant.channel_all) && isFirstLoad) {
            isFirstLoad = false;
            getbbPost(currPage); //全部频道
            getBannerList();
        }

        if (topic_type == BBConstant.TOPIC_TYPE_EDG && isFirstLoad) {
            isFirstLoad = false;
            getEdg(currPage);
            getBannerList();
        }

        bbAdapter.setOnItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
            }
        });

    }

    private boolean edgLoading = false;

    private void getEdg(int page) {
        if (edgLoading) {
            return;
        }
        User user = userPrefUtils.getUser();
        PostsParam nearbyParam = new PostsParam();
        String tmp = "";
        if(currPage!=1 && topicList.size()>0){
            tmp = "timestamp|"+ topicList.get(topicList.size()-1).getCreateAt();
        }
        nearbyParam.setParamsValue(tmp);
        nearbyParam.setPage(page + "");
        nearbyParam.setPageSize(pageSize + "");
        nearbyParam.setUserId(user.getId() + "");
        if (topic_type == BBConstant.TOPIC_TYPE_EDG) {
            topicApi.getEdgPost(nearbyParam, new getedgListener("bb"));//edg列表
        } else if (topic_type == BBConstant.TOPIC_TYPE_CHANNEL) {
            if (channel.getChannelId().equals(BBConstant.channel_all)) {
                getbbPost(page); //全部频道
            } else if (channel.getChannelId().equals(BBConstant.channel_attention)) {
                topicApi.attentionPost(nearbyParam, new getedgListener("bb"));//关注列表
            } else {
                getChannelPost(page, channel.getParams(), channel.getProtocol()); //频道列表
            }
        }

//        if(page==1){ //获取banner
//            getBannerList();
//        }
    }

    private void getbbPost(int page) {
        PostsParam hotParam = new PostsParam();
        String tmp = "";
        if(currPage!=1 && topicList.size()>0){
            tmp = "timestamp|"+ topicList.get(topicList.size()-1).getCreateAt();
        }
        hotParam.setParamsValue(tmp);
        hotParam.setPage(page + "");
        hotParam.setPageSize(pageSize + "");
        hotParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.getbbPost(hotParam, new getedgListener("bb"));
    }

    private void getChannelPost(int page, String paramsValues, String url) {
        PostsParam myParam = new PostsParam();
        String tmp = "";
        if(currPage!=1 && topicList.size()>0){
            tmp = "timestamp|"+ topicList.get(topicList.size()-1).getCreateAt();
        }
        myParam.setParamsValue(paramsValues+","+tmp);
        myParam.setPage(page + "");
        myParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.channelPost(myParam, url, new getedgListener("channel"));
    }

    /**
     * 获取banner
     */
    private void getBannerList(){
        PostsParam param = new PostsParam();
        param.setUserId(userPrefUtils.getUser().getId()+"");
        if (topic_type == BBConstant.TOPIC_TYPE_EDG) {
            param.setSource(BBConstant.BANNER_TYPE_EDG+"");
        } else if (topic_type == BBConstant.TOPIC_TYPE_CHANNEL) {
            param.setSource(BBConstant.BANNER_TYPE_BB+"");
        }
        topicApi.getBannerList(param, new getBannerListListener());
    }

    private void likePost(String topicId) {
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.likePost(postsParam, new getlikeListener());
    }

    private void unlikePost(String topicId) {
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.unlikePost(postsParam, new getlikeListener());
    }

    private void initHeadView(View view){
//        ll_banner = (FrameLayout) view.findViewById(R.id.ll_banner);
//        banner_viewPager = (AutoScrollViewPager) view.findViewById(R.id.view_pager);
//        viewGroup = (LinearLayout) view.findViewById(R.id.viewGroup);
//        bannerCommon = new BannerComponent();
//        bannerCommon.init(mActivity,banner_viewPager,viewGroup);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_refresh:
                break;

        }
    }

    // 刷新频道
    @Subscribe
    public void bbRefreshEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.BB_REFRESH.equals(event)) {
            if (getUserVisibleHint()) {
                if (edgLoading) {
                    return;
                }
                recyclerView.scrollToPosition(0);
                recyclerView.setRefreshing(true);
            }
        }
    }

    // 创建新的贴子
    @Subscribe
    public void createTopicEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICCREATENEOTOPIC.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            topic.setState("1");

            if(topicList.contains(topic)){//修改
                int index = topicList.indexOf(topic);
                topicList.add(index,topic);
                topicList.remove(index+1);
                Toast.makeText(getActivity(),"修改成功",Toast.LENGTH_SHORT).show();
            }else{

                if (topic_type == BBConstant.TOPIC_TYPE_EDG && userPrefUtils.getUser().getUserAuth().getType().equals("0")) {
                    topicList.add(0,topic); //新增帖子
                    Toast.makeText(getActivity(),"发帖成功",Toast.LENGTH_SHORT).show();
                }
                if (channel!=null && channel.getTitle().equals("大咖") && userPrefUtils.getUser().getUserAuth().getType().equals("1")) {
                    topicList.add(0,topic); //新增帖子
                    Toast.makeText(getActivity(),"发帖成功",Toast.LENGTH_SHORT).show();
                }
                if(channel!=null && channel.getTitle().equals("约黑") && topic.getBlack().equals("1")){
                    topicList.add(0,topic); //新增帖子
                    Toast.makeText(getActivity(),"发帖成功",Toast.LENGTH_SHORT).show();
                }
                if(channel!=null && channel.getChannelId() == BBConstant.channel_all
                        && !userPrefUtils.getUser().getUserAuth().getType().equals("0") &&
                        !userPrefUtils.getUser().getUserAuth().getType().equals("1")
                    && !topic.getBlack().equals("1")){
                    topicList.add(0,topic); //新增帖子
                    Toast.makeText(getActivity(),"发帖成功",Toast.LENGTH_SHORT).show();
                }

                MobclickAgent.onEvent(getActivity(),"EC_POST_CREATE_SUCCESS");
            }
//            bbAdapter.setDatas(topicList);
            bbAdapter.notifyDataSetChanged();
        }
    }


    // 删除贴子
    @Subscribe
    public void deleteTopicEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICDELETETOPIC.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            if(topicList.contains(topic)){
                topicList.remove(topic);
            }
//            bbAdapter.setDatas(topicList);
            bbAdapter.notifyDataSetChanged();
        }
    }

    // 更新点赞 贴子
    @Subscribe
    public void updateLikeEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICLIKE.equals(event) || BroadCastEvent.TOPIC_UNLIKE.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            if(topicList.contains(topic)){
                int index = topicList.indexOf(topic);
                Topic topic1 = topicList.get(index);
                topic1.setLiked(topic.getLiked());
                topic1.setLikes(topic.getLikes());
                bbAdapter.notifyDataSetChanged();
            }
        }
    }

    // 更新评论数 贴子
    @Subscribe
    public void updateReplysEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICREPLYS.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            if(topicList.contains(topic)){
                int index = topicList.indexOf(topic);
                Topic topic1 = topicList.get(index);
                topic1.setReplys(topic.getReplys());
                bbAdapter.notifyDataSetChanged();
            }
        }
    }

    // 加精
    @Subscribe
    public void adddigestTopicEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICADDDIGEST.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            if(topicList.contains(topic)){
                int index = topicList.indexOf(topic);
                Topic topic1 = topicList.get(index);
                topic1.setNice(topic.getNice());
                bbAdapter.notifyDataSetChanged();
            }
        }
    }

    // 更新红包状态
    @Subscribe
    public void updateRedStateEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.TOPICREDSTATE.equals(event)) {
            Topic topic = (Topic) map.get("topic");
            if(topicList.contains(topic)){
                int index = topicList.indexOf(topic);
                Topic topic1 = topicList.get(index);
                topic1.setRedState("1");
                bbAdapter.notifyDataSetChanged();
            }
        }
    }


    class getedgListener implements VolleyListener {

        String type;

        public getedgListener(String type) {
            this.type = type;
        }

        @Override
        public void onStart(String tag) {
            edgLoading = true;
        }

        @Override
        public void onSuccess(String response, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setLoadViewGONE();
            if (JSONHelper.isSuccess(response)) {
                ArrayList<Topic> topics = null;
                if (type.equals("bb")) {
                    TopicBBData data = JsonUtil.getMode(response,
                            TopicBBData.class);
                    topics = data.getData().getPosts();
                } else if (type.equals("channel")) {
                    TopicListData data = JsonUtil.getMode(response, TopicListData.class);
                    topics = data.getData();
                }
                if (topics != null && topics.size() > 0) {
                    if (currPage == 1) {
                        topicList.clear();
                    }
                    //分离图片语音
                    for(int i=0;i<topics.size();i++){
                        Topic topic = topics.get(i);
                        ArrayList<PostsAlbum> audios = new ArrayList<>();
                        ArrayList<PostsAlbum> albums = new ArrayList<>();
                        final ArrayList<PostsAlbum> tmpalbums = topic.getAlbums();
                        if (tmpalbums != null && tmpalbums.size() > 0) {
                            for (PostsAlbum postsAlbum : tmpalbums) {
                                if (postsAlbum.getUrl().contains(
                                        BBConstant.URL_VOICE_PROTOCOL)) {
                                    audios.add(postsAlbum);
                                }else if(postsAlbum.getUrl().contains(
                                        BBConstant.URL_VIDEO_PROTOCOL)){
                                    topic.setCategory("1");
                                    albums.add(postsAlbum);
                                    if(topic.getVideo()==null){
                                        topic.setVideo(postsAlbum);
                                    }
                                } else{
                                    albums.add(postsAlbum);
                                }
                            }
                        }
                        topic.setAlbums(albums);
                        topic.setAudios(audios);
                    }
                    topicList.addAll(topics);
                    currPage++;
                    bbAdapter.notifyDataSetChanged();
                }else{
                    recyclerView.noMoreLoading();
                }
            } else {

            }
            if (!"".equals(topicList)&&topicList.size()>0){
                layout_empty.setVisibility(View.GONE);
                recyclerView.setPullRefreshEnabled(true);
            }
            else {
                layout_empty.setVisibility(View.VISIBLE);
                recyclerView.setPullRefreshEnabled(false);
                layout_empty.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, Object> hashMap = new HashMap<String, Object>();
                        hashMap.put("event", BroadCastEvent.USERFIND);
                        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON, ThreadEnforcer.MAIN).post(hashMap);
                    }
                });
            }

        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setNoNetWork(new ReLoadClickListener() {
                @Override
                public void reload() {
                    getEdg(currPage);
                }
            });
            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }


    class getlikeListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
        }

        @Override
        public void onSuccess(String response, String tag) {
            if (JSONHelper.isSuccess(response)) {
                if (tag.equals((ApiConfig.APIURL.URL_POSTS_LIKE))) {
                    AaskBeanData aaskBeanData = JsonUtil.getMode(response, AaskBeanData.class);
                    if (null != aaskBeanData && aaskBeanData.getTaskData().size() > 0) {
                        for (AaskBeanData.AaskBean bean : aaskBeanData.getTaskData()) {
                            StringUtils.postToast2(getActivity(), bean.getName() + "", bean.getGold() + "");
                        }
                    }
                } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_UNLIKE))) {

                }
            } else {

            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
//            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }

    class getBannerListListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
        }

        @Override
        public void onSuccess(String response, String tag) {
//            if (JSONHelper.isSuccess(response)) {
//                if (tag.equals((ApiConfig.APIURL.URL_POSTS_BANNER_LIST))) {
//                    BannerListData data = JsonUtil.getMode(response, BannerListData.class);
//                    ArrayList<Banner> banners = data.getData();
//                    if(banners!=null && banners.size()>0){
//                        ll_banner.setVisibility(View.VISIBLE);
//                        bannerCommon.setBanners(banners);
//                    }else{
//                        ll_banner.setVisibility(View.GONE);
//                    }
//                }
//            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
//            edgLoading = false;
//            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

}
